package org.tloss.web.editor.editors.configuration;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.tloss.web.editor.Utils;
import org.tloss.web.editor.utils.Constants;

public class ConfigurationMainEditor extends EditorPart implements
		IResourceChangeListener {
	private boolean dirty = false;
	private Properties properties = new Properties();
	TreeViewer treeViewer;

	public ConfigurationMainEditor() {
		properties.putAll(Constants.DEFAULT_CONFIG);

	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		IEditorInput editorInput = this.getEditorInput();
		IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput;
		IFile file = fileEditorInput.getFile();

		try {
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			properties.store(arrayOutputStream, "Project Configuration");

			file.setContents(
					new ByteArrayInputStream(arrayOutputStream.toByteArray()),
					false, true, monitor);
			this.dirty = false;
			this.firePropertyChange(IEditorPart.PROP_DIRTY);
		} catch (CoreException e) {
			Utils.logError("Fail to save Configuration", e);
		} catch (IOException e) {
			Utils.logError("Fail to save Configuration", e);
		}
	}

	@Override
	public void doSaveAs() {

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		if (!(input instanceof IFileEditorInput)) {
			PartInitException exception = new PartInitException(
					"Input must be a file");
			Utils.logError("Input must be a file", exception);
			throw exception;
		}
		setSite(site);
		setInput(input);
		IFileEditorInput editorInput = (IFileEditorInput) input;
		IFile file = editorInput.getFile();

		InputStream inputStream = null;
		try {
			inputStream = file.getContents();
			if (inputStream.available() > 0) {
				properties.load(inputStream);
			}
		} catch (CoreException e) {
			PartInitException exception = new PartInitException(
					"Can't load resource", e);
			Utils.logError("Can't load resource", exception);
			throw exception;
		} catch (IOException e) {
			PartInitException exception = new PartInitException(
					"Can't load resource", e);
			Utils.logError("Can't load resource", exception);
			throw exception;
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				Utils.logError("Can't close inputstream", e);
			}
		}
	}

	@Override
	public boolean isDirty() {

		return dirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	public void createPartControl(final Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		composite.setLayout(layout);
		layout.numColumns = 2;

		Composite treeContainer = new Composite(composite, SWT.BORDER);
		GridData gridData = new GridData();
		treeContainer.setLayoutData(gridData);
		gridData.horizontalAlignment = SWT.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.verticalAlignment = SWT.FILL;
		gridData.grabExcessVerticalSpace = true;
		TreeColumnLayout treeLayout = new TreeColumnLayout();
		treeContainer.setLayout(treeLayout);
		treeViewer = new TreeViewer(treeContainer, SWT.MULTI
				| SWT.FULL_SELECTION);
		Tree tree = treeViewer.getTree();
		tree.setHeaderVisible(true);
		TreeColumn keyColumn;
		TreeColumn valueColumn;

		keyColumn = new TreeColumn(tree, SWT.NONE);
		keyColumn.setText("Name");
		treeLayout.setColumnData(keyColumn, new ColumnWeightData(2));

		valueColumn = new TreeColumn(tree, SWT.NONE);
		valueColumn.setText("Value");
		treeLayout.setColumnData(valueColumn, new ColumnWeightData(2));

		treeViewer.setContentProvider(new PropertyProvinder());
		final PropertyLabelProvider treeLabelProvider = new PropertyLabelProvider();
		treeViewer.setLabelProvider(treeLabelProvider);

		TreeViewerColumn column1 = new TreeViewerColumn(treeViewer, keyColumn);

		column1.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return treeLabelProvider.getColumnText(element, 0);
			}

			public Image getImage(Object element) {

				return treeLabelProvider.getImage(element);
			}
		});

		column1.setEditingSupport(new EditingSupport(treeViewer) {

			TextCellEditor editor = new TextCellEditor((Composite) treeViewer
					.getControl());

			protected boolean canEdit(Object element) {
				return true;
			}

			protected CellEditor getCellEditor(Object element) {

				return editor;
			}

			protected Object getValue(Object element) {
				return treeLabelProvider.getColumnText(element, 0);
			}

			@SuppressWarnings("rawtypes")
			protected void setValue(Object element, Object value) {
				try {
					Object text = value;
					if (text != null) {
						if (element != null && element instanceof Entry) {
							Entry field = ((Entry) element);
							if (field.getKey() != null
									&& !field.getKey().equals(text)) {
								Object val = field.getValue();
								properties.remove(field.getKey());
								properties.put(text, val);
								treeModified(null);
							}
						}
					}
				} catch (Exception e) {
					Utils.logError("Error", e);
				}

			}

		});

		TreeViewerColumn column2 = new TreeViewerColumn(treeViewer, valueColumn);
		column2.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return treeLabelProvider.getColumnText(element, 1);
			}

			public Image getImage(Object element) {

				return treeLabelProvider.getImage(element);
			}
		});

		column2.setEditingSupport(new EditingSupport(treeViewer) {

			TextCellEditor editor = new TextCellEditor((Composite) treeViewer
					.getControl());

			protected boolean canEdit(Object element) {
				return true;
			}

			protected CellEditor getCellEditor(Object element) {

				return editor;
			}

			protected Object getValue(Object element) {
				return treeLabelProvider.getColumnText(element, 1);
			}

			@SuppressWarnings("rawtypes")
			protected void setValue(Object element, Object value) {

				Object text = value;
				if (element instanceof Entry) {
					Entry field = ((Entry) element);
					if (field.getValue() != null || text != null) {
						if ((text != null && !text.equals(field.getValue()))
								|| (field.getValue() != null && !field
										.getValue().equals(text))) {
							properties.put(field.getKey(), text);
							treeModified(null);
						}
					}
				}

			}
		});

		getSite().setSelectionProvider(treeViewer);

		treeViewer.setInput(properties);

		treeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS);

		Composite wrapper = new Composite(composite, SWT.NONE);
		RowLayout rowLayout = new RowLayout();
		wrapper.setLayout(rowLayout);
		rowLayout.type = SWT.VERTICAL;

		Button button = new Button(wrapper, SWT.NONE);
		button.setText("Add");
		Button buttonDelete = new Button(wrapper, SWT.NONE);
		buttonDelete.setText("Delete");

		buttonDelete.addMouseListener(new MouseListener() {

			@Override
			public void mouseUp(MouseEvent e) {

			}

			@SuppressWarnings("unchecked")
			@Override
			public void mouseDown(MouseEvent e) {
				TreeItem[] items = treeViewer.getTree().getSelection();
				for (int i = 0; i < items.length; i++) {
					properties.remove(((Entry) items[i]
							.getData()).getKey());
				}
				treeModified(null);

			}

			@Override
			public void mouseDoubleClick(MouseEvent e) {

			}
		});
		button.addMouseListener(new MouseListener() {

			@Override
			public void mouseUp(MouseEvent e) {

			}

			@Override
			public void mouseDown(MouseEvent e) {
				properties.put("Key_" + System.currentTimeMillis(), "value");
				treeModified(null);

			}

			@Override
			public void mouseDoubleClick(MouseEvent e) {

			}
		});
	}

	@Override
	public void setFocus() {

	}

	public void treeModified(Object element) {
		if (element == null)
			treeViewer.refresh();
		else
			treeViewer.refresh(element);
		dirty = true;
		firePropertyChange(IEditorPart.PROP_DIRTY);

	}

	@Override
	public void resourceChanged(IResourceChangeEvent event) {
		treeModified(null);
	}
}
